package com.smbms.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.smbms.entity.Role;
import com.smbms.entity.User;
import com.smbms.service.RoleService;
import com.smbms.service.UserService;
import com.smbms.tool.Constants;
import com.smbms.tool.ExcelUtil;
import com.smbms.tool.PageSupport;
import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable;

@Controller
@RequestMapping("user")
public class UserController {
	@Resource
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	private String downUserName;
	
	private Integer downUserRole = 0;
	
	
	
	
	//进入用户列表页面
		@RequestMapping("userlist")
		public String userList(String queryUserName,String queryUserRole,String pageIndex,Model model) throws IOException{
			//因为第一次点击用户列表的时候,用户名,用户角色都是为空的.
			int _queryUserRole = 0;
			if(queryUserRole != null){
				_queryUserRole = Integer.valueOf(queryUserRole);
				downUserRole = Integer.valueOf(queryUserRole);
			}
			if(queryUserName==null){
				queryUserName = ""; 
			}
			
			int currentPageNo = 1;	//当前页码
			int pageSize  = Constants.pageSize;	//数据显示大小
			
			if(pageIndex!=null){
				currentPageNo = Integer.valueOf(pageIndex);
			}
			
			List<User> userList = userService.getUserList(queryUserName, _queryUserRole, currentPageNo, pageSize);
			
			
			
			int totalCount = userService.getUserCount(queryUserName, _queryUserRole);
			PageSupport page = new PageSupport();
			page.setCurrentPageNo(currentPageNo);	//当前页码
			page.setPageSize(pageSize);	//每页显示大小
			page.setTotalCount(totalCount);	//总数量
			int totalPageCount = page.getTotalPageCount();	//总页码
			
			//控制上下页
			if(currentPageNo < 1){
				currentPageNo = 1;
			}else if(currentPageNo>totalPageCount){
				currentPageNo=totalPageCount;
			}
			List<Role> roleList = roleService.getRoleList();
			model.addAttribute("roleList", roleList);
			model.addAttribute("userList", userList);
			model.addAttribute("totalCount", totalCount);
			model.addAttribute("currentPageNo", currentPageNo);
			model.addAttribute("totalPageCount", totalPageCount);
			model.addAttribute("queryUserName", queryUserName);	//点击查询,还会继续显示在页面上
			model.addAttribute("queryUserRole", _queryUserRole);	//点击查询,还会继续显示在页面上
			return "userlist";
		}

	
		//根据ID查看用户信息
		@RequestMapping("view")
		public String view(String id,Model model){
			User user = userService.getUserListById(Integer.valueOf(id));
			model.addAttribute(user);
			return "userview";
		}
		
		//根据ID删除用户信息
		@RequestMapping("userdelete")
		@ResponseBody
		public Object userDelete(String id){
			Map<String,String> map = new HashMap<String,String>();
			if(userService.deleteUser(Integer.valueOf(id))){	//删除成功
				map.put("delResult", "true");
			}else{
				map.put("delResult", "false");
			}
			return map;
		}
		
		//先进入到修改页面,并显示该用户的信息
		@RequestMapping("modify")
		public String modify(String id,Model model){
			User user = userService.getUserListById(Integer.valueOf(id));
			model.addAttribute(user);
			return "usermodify";
		}
		
		//修改页面中,点击保存修改信息
		@RequestMapping("usermodifysave")
		public String userModifySave(User user){
			if(userService.updateUser(user)){
				return "redirect:/user/userlist";	//修改成功重定向用戶列表
			}
			return "usermodify";
		}
		
		//json获取角色列表
		@RequestMapping("userrole")
		@ResponseBody
		public Object userRole(){
			return roleService.getRoleList();
		}
		
		//先进入添加用户页面
		@RequestMapping("useradd")
		public String userAdd(){
			return "useradd";
		}
		
		//json验证添加用户的账号唯一性
		@RequestMapping("userexist")
		@ResponseBody
		public Object userExist(String userCode){
			Map<String,String> map = new HashMap<String,String>();
			User user = userService.getUserListByUserCode(userCode);
			if(user == null){	//user为null,表示可以添加
				map.put("exist", "false");
			}else{
				map.put("exist", "true");
			}
			return map;
		}
		
		//添加页面中,点击添加
		@RequestMapping("useraddsave")
		public String userAddSave(User user,@RequestParam(value="attachs",required=false)MultipartFile[] attachs,HttpServletRequest request){
			String picPath = null;	//证件照
			String workPath = null;	//工作照
			String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
			String error = null;
			for (int i = 0; i < attachs.length; i++) {
				MultipartFile attach = attachs[i];
				if(!attach.isEmpty()){	//判断是否存在
					if(i == 0){
						error = "uploadFileError";
					}else if(i == 1){
						error = "uploadWpError";
					}
					String oldFileName = attach.getOriginalFilename();	//获取原文件名字
					String prefix = FilenameUtils.getExtension(oldFileName);	//获取后缀
					int fileSize = 500000;
					if(attach.getSize() > fileSize){	//判断大小
						request.setAttribute(error, "*上传文件大小不能超过500KB");
						return "useradd";
					}else if(prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")){	//判断后缀
						String fileName = UUID.randomUUID().toString() + user.getUserName() + ".jpg";	//重写文件名
						File file = new File(path,fileName);
						if(!file.exists()){	//如果不存在,就创建一个
							file.mkdirs();
						}
						try {
							attach.transferTo(file);
						} catch (Exception e) {
							e.printStackTrace();
							request.setAttribute(error, "*上传失败");
							return "useradd";
						}
						if(i == 0){
							picPath = path + File.separator + fileName;
						}else if(i == 1){
							workPath = path + File.separator + fileName;
						}
					}else{
						request.setAttribute(error, "*上传图片格式不正确");
						return "useradd";
					}
				}
			}
			int userId = ((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId();
			user.setCreatedBy(userId);
			user.setCreationDate(new Date());
			user.setIdPicPath(picPath);
			user.setWorkPicPath(workPath);
			if(userService.addUser(user)){
				return "redirect:/user/userlist";	//添加成功就重定向到用户列表
			}
			return "useradd";
		}
		
		//进入修改密码页面
		@RequestMapping("pwdmodify")
		public String pwdModify(){
			return "pwdmodify";
		}
		
		//json验证原密码是否输入正确
		@RequestMapping("userpwd")
		@ResponseBody
		public Object userPwd(String oldpassword,HttpSession session){
			int userId = ((User)session.getAttribute(Constants.USER_SESSION)).getId();	//通过保存在session的登录用户获取id
			//再根据id获取用户信息,判断原密码是否输入正确
			User user = userService.getUserListById(userId);
			Map<String,String> map = new HashMap<String,String>();
			if(user.getUserPassword().equals(oldpassword)){		//原密码输入正确
				map.put("result", "true");
			}else{
				map.put("result", "false");
			}
			return map;
		}
		
		//修改密码页面中,点击修改
		@RequestMapping("pwdsave")
		public String pwdSave(String newpassword,HttpSession session){
			User user = new User();
			int userId = ((User)session.getAttribute(Constants.USER_SESSION)).getId();	//通过保存在session的登录用户获取id
			//再根据id修改用户密码
			user.setId(userId);
			user.setUserPassword(newpassword);
			if(userService.updateUserPwd(user)){
				return "redirect:/login";	//修改成功,则重定向到登录页面重新登录
			}
			return "pwdmodify";
		}
		 
		
		
		
		@RequestMapping("/downloadFile")     
	    public ResponseEntity<byte[]> download(HttpServletRequest req) throws IOException { 
	    	
	        
	    	
	    	List<User> userList = userService.download(downUserName, downUserRole);
			//下载先把数据写入excel表格
	    	String path = new ExcelUtil().writerExcel(userList );
	    	
	        File file=new File(path);  
	        HttpHeaders headers = new HttpHeaders();    
	        String fileName=new String(path.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
	        headers.setContentDispositionFormData("attachment", fileName);   
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
	        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
	                                          headers, HttpStatus.CREATED);    
	    } 
	   
	    
	    
}
